<?php


namespace app\zhongcan\controller;



use app\zhongcan\model\TitleModel;

use app\zhongcan\validate\titleValidate;
use cmf\controller\AdminBaseController;

class titleController extends AdminBaseController
{
    public function index(){
        $keyname = input('checkname');
        $where = [];
        if ($keyname){
            $where[] = ['title', 'like','%'.$keyname.'%' ];
        }
        $data = TitleModel::order('list_order','DESC')->paginate('6');
        $page = $data->render();
        return $this->fetch('index', [
            'title' => $data,
            'page'  => $page,
        ]);
    }

    public function order(){
        parent::listOrders(new TitleModel());
        $this->success('排序成功');
    }

    public function toggleSwitch()
    {
        $id = $this->request->param('id', 1, 'intval');
        $news = TitleModel::find($id);
        if ($news) {
            $news->switch = $news->switch ? 0 : 1;
            if ($news->save()) {
                return json(['status' => 1, 'msg' => '状态切换成功', 'switch' => $news->switch]);
            } else {
                return json(['status' => 0, 'msg' => '状态切换失败']);
            }
        } else {
            return json(['status' => 0, 'msg' => '新闻不存在']);
        }
    }

    public function add(){
        return $this->fetch();
    }
    public function addPost(){
        $data = input('post.');
        $validate = new titleValidate();
        $res = $validate->scene('add')->check($data);
        if (!$res){
            $this->error($validate->getError());
        }else{
            if (TitleModel::create($data)){
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }

        }
    }
    public function edit(){
        $id = input('id/d');
        $data = TitleModel::find($id);
        return $this->fetch('edit',[
            'title' => $data
        ]);
    }

    public function editPost(){
        if($this->request->ispost()){
            $data = $this->request->post();

            $validate = new titleValidate();
            $val = $validate->scene('edit')->check($data);
            if (!$val){
                $this->error($validate->getError());
            }
            $titledata = TitleModel::find($data['id']);
            if (!$titledata){
                $this->error('该题目不存在');
            }
            $titledata->title = $data['title'];
            $titledata->part_id = $data['part_id'];
            $titledata->url = $data['url'];
            if($titledata->save()){
                $this->success('修改成功');
            }else{
                $this->error('修改失败');
            }
        }
    }

    public function delete(){
        $id = input('id/d');
         if(TitleModel::destroy($id)){
             $this->success('删除成功');
         }else{
             $this->error('删除失败');
         }

    }
}